package com.witmore.skyline.web.service.third.yjx.client;

import com.alibaba.fastjson.JSONObject;
import com.witmore.skyline.web.controller.enums.WitmoreErrorCode;
import com.witmore.skyline.web.exception.WitmoreException;
import com.witmore.skyline.web.service.third.constants.ApiClientCommonConstant;
import com.witmore.skyline.web.service.third.yjx.dto.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Description: ApiClient 第三方接口调用
 * Author: 豆子高
 * Date: 2025/2/24 14:26
 */
@Slf4j
public class ApiClient {

    public static String responseHandle(String urlString, String methodName) {
        log.info("请求url：{}", urlString);
        String responseStr = httpConnection(urlString, ApiClientCommonConstant.METHOD_GET);
        log.info("{} responseStr:{}", methodName, responseStr);
        ApiResponse apiResponse = JSONObject.parseObject(responseStr, ApiResponse.class);
        if (null == apiResponse || 800 != apiResponse.getCode()) {
            log.error("api {}调用失败,失败原因：{}", methodName, responseStr);
            if (null != apiResponse) {
                throw new WitmoreException(WitmoreErrorCode.THIRD_PARTY_API_ERROR, apiResponse.getMessage());
            } else {
                throw new WitmoreException(WitmoreErrorCode.THIRD_PARTY_API_ERROR);
            }
        }
        if (ObjectUtils.isEmpty(apiResponse.getResult())) {
            return null;
        }
        return apiResponse.getResult().toString();
    }

    public static String httpConnection(String urlString, String method) {
        log.info("请求url：{}", urlString);
        String responseStr = httpConnectionHandler(urlString, method);
        ApiResponse apiResponse = JSONObject.parseObject(responseStr, ApiResponse.class);
        // code=-10086 token不存在
        if (null != apiResponse && -10086 == apiResponse.getCode()) {
            int retryCount = 0;
            while (retryCount < 1) {
                log.info("Token expired, reacquiring token.");
                // 重新获取token
                TokenCache.refreshToken();
                // 重新请求
                urlString = urlString.replaceFirst("token=[^&]+", "token=" + TokenCache.getToken());
                responseStr = httpConnectionHandler(urlString, method);
                retryCount += 1;
            }
            log.warn("重试请求-->{}次", retryCount);
        }
        return responseStr;
    }

    /**
     * 接口调用工具
     *
     * @param urlString
     * @param method
     */
    public static String httpConnectionHandler(String urlString, String method) {
        try {
            // 创建 URL 对象
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方式为
            connection.setRequestMethod(method);

            // 设置连接超时时间和读取超时时间
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            // 获取响应码
            int responseCode = connection.getResponseCode();
            // 读取响应内容
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                // 打印响应结果
                String responseStr = response.toString();
                log.info("Response:{}", responseStr);
                return responseStr;
            } else {
                log.warn("GET request failed.");
            }
        } catch (IOException e) {
            log.error("GET request failed.", e);
        }
        return null;
    }


}
